<template>
  <view class="content">
	  <u-navbar :is-back="false" title="考勤打卡"
	    title-size="30"
	    :background="{background:'#2B88FE' }"
	    title-color="#fff">
	    <div class="head_icon">
	      <u-icon @click="$api.handleBackTo"
	        name="arrow-left" color="#fff"
	        size="36">
	      </u-icon>
	      <u-icon @click="$api.handleHomeTo"
	        name="home" color="#fff" size="36">
	      </u-icon>
	    </div>
	  </u-navbar>
    <view class="x-row boxcolor">
      <view class="l_text" @click="clhref">考勤统计</view>
      <view class="x-col"></view>
      <view class="x-col-center">
        <view class="itemna">{{date}}</view>
        <!-- <picker mode="date" :end="endDate" fields="month" @change="dateChange">
          <view class="x-row">
            <u-icon name="arrow-left" class="x-col-center" color="#fff" size="28"
              style="opacity: 0.7;"></u-icon>
            <view class="itemna">{{date}}</view>
            <u-icon name="arrow-right" class="x-col-center" color="#fff" size="28"
              style="opacity: 0.7;"></u-icon>
          </view>
        </picker> -->
      </view>
    </view>
    <view class="shownyber x-row" @click="clhref">
      <view class="x-col">
        <view class="nunber">{{info.days}}</view>
        <view class="n_text">出勤天数</view>
      </view>
      <view class="x-col">
        <view class="nunber">{{info.late}}</view>
        <view class="n_text">迟到</view>
      </view>
      <view class="x-col">
        <view class="nunber">{{info.leave_early}}</view>
        <view class="n_text">早退</view>
      </view>
      <view class="x-col">
        <view class="nunber">{{info.leave}}</view>
        <view class="n_text">请假</view>
      </view>
      <view class="x-col">
        <view class="nunber">{{info.miss}}</view>
        <view class="n_text">缺卡</view>
      </view>
    </view>
    <uni-calendar class="uni-calendar--hook" :date="date" @monthSwitch="monthSwitch"
      :selected="form.selected" :showMonth="false" />
    <view style="color:#333; font-size: 32upx; padding: 48upx 32upx 20upx 32upx">考勤打卡</view>
    <view class="punchtheclock">
      <view class="layers">
        <view class="text1" :class="{text4:form.work}">上班时间 {{form.work?'已打卡':'未打卡'}}</view>
        <view style="height:60rpx"></view>
        <view class="text1 " :class="{text4:form.afternoon}">下班时间 {{form.afternoon?'已打卡':'未打卡'}}
        </view>
      </view>
    </view>

    <view class="buttonbox" @click="clockThis" v-if="info.is_connect==0">
      <view style="font-size: 36upx;">{{!ismorning?'下班打卡':'上班打卡'}}</view>
      <view style="font-size: 26upx;">{{showTime}}</view>
    </view>
    <view class="buttonbox" @click="Wfield" v-if="info.is_connect==2">
      <view style="font-size: 36upx;">外勤打卡</view>
      <view style="font-size: 26upx;">{{showTime}}</view>
    </view>
  </view>
</template>

<script>
function getDate(date, AddDayCount = 0) {
  if (!date) {
    date = new Date()
  }
  if (typeof date !== 'object') {
    date = date.replace(/-/g, '/')
  }
  const dd = new Date(date)

  dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

  const y = dd.getFullYear()
  const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
  return {
    fullDate: y + '-' + m + '-' + d,
    year: y,
    month: m,
    date: d,
    day: dd.getDay()
  }
}

var inval = ''
export default {
  data() {
    return {
      src: '',
      isWifi: '',
      isGps: '',
      dateInfo: {
        Year: new Date().getFullYear(),
        Month: new Date().getMonth() + 1
      },
      info: {
        WifiName: '',
        WifiCode: '',
        Lat: '',
        Lon: '',
        Address: '',
        Info: '',
        Pic: '',
        is_connect: 0
      },
      endDate: '',
      showTime: '',
      form: {
        work: 0,
        afternoon: 0,
        selected: []
      },
      ismorning: true
    }
  },
  onLoad() {
    let ismorning = new Date().toLocaleTimeString().substr(0, 2) === '上午'
    this.ismorning = ismorning
    let dateMonth = new Date().toLocaleDateString().split('/').splice(0, 2).join('-')
    this.date = dateMonth
    this.endDate = this.date
    this.$api.getUserLoacation(res => {
      let info = res.result
      this.info.Lat = info.location.lat
      this.info.Lon = info.location.lng
      this.info.Address = info.address
    })
  },
  onShow() {
    let that = this
    this.getWifiGps()
    setInterval(function () {
      var date = new Date()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      that.showTime = h + ':' + m + ':' + s
    }, 1000)
  },
  methods: {
    monthSwitch(e) {
      this.dateInfo = e
      this.date = Object.values(e)
        .map(x => (x < 10 ? '0' + x : x))
        .join('-')
      this.loadInfo()
    },
    clockThis() {
      console.log(this.info)
      this.$axios('api/UserClock/AddDetail', 'post', { value: this.info }).then(res => {
        if (res.Message === '您今天已打卡') {
          uni.showToast({
            title: res.Message,
            duration: 2000
          })
        } else {
          uni.showToast({
            title: '打卡成功',
            duration: 2000
          })
          this.loadInfo()
        }
      })
    },
    dateChange(e) {
      let dates = e.detail.value.split('-')
      this.date = e.detail.value
      this.dateInfo = { Year: dates[0], Month: dates[1] }
      this.loadInfo()
    },
    clhref() {
      uni.navigateTo({
        url: './Punchinrecord?date=' + this.date
      })
    },
    Wfield() {
      // uni.navigateTo({
      // 	url: "./Clockoutinthefield"
      // })
      // 外勤打卡
      let that = this
      this.$api.getUserLoacation(function (res) {
        uni.navigateTo({
          url: 'Clockoutinthefield?lat=' + res.latitude + '&lon=' + res.longitude
        })
      })
    },
    getTimeOut(callback) {
      var that = this,
        two = 0
      inval = setInterval(() => {
        // console.log("interval 1")
        if (two <= 1) {
          that.getWifiGps()
          two += 1
        } else {
          clearInterval(inval)
        }
      }, 500)
    },
    // 回调函数分别 调用 设备方法，wifi获取参数接口
    getWifiGps() {
      var that = this
      that.getPhoneSystemInfo(function () {
        if (that.isWifi && that.isGps) {
          that.startWifi(function () {
            that.connection(function () {
              that.loadInfo()
            })
          })
        } else {
          that.loadInfo()
        }
      })
    },
    loadInfo() {
      this.$axios('api/UserClock/CkeckClock', 'post', { value: 0 }).then(res => {
        this.form.work = res.Value
      })
      this.$axios('api/UserClock/CkeckClock', 'post', { value: 1 }).then(res => {
        this.form.afternoon = res.Value
      })
      this.$axios('api/UserClock/UserClockList', 'post', {
        value: this.dateInfo
      }).then(res => {
        this.form.selected = res.Value.map(x => ({
          date: x.dTime.substr(0, 10),
          info: this.getinfo(x)
        }))
      })
    },
    getTimeText(date) {
      var date1 = new Date(date) //要对比的时间
      var date2 = new Date() //获取当前时间对象
      // var num = 24 * 60 * 60 * 1000 //一天的毫秒数
      var cha = date2.getTime() - date1.getTime() //两个时间的毫秒差
      if (cha < 0) {
        console.log('是未来时间')
        return true
      }
    },
    getinfo(x) {
      if (this.getTimeText(x.dTime)) return ''
      return x.AmTime ? '已打卡' : x.AmInfo
    },
    // 设备开关 是否打开wifi 和gps定位开关
    getPhoneSystemInfo(callback) {
      var that = this
      wx.getSystemInfo({
        success(res) {
          that.isWifi = res.wifiEnabled ? res.wifiEnabled : ''
          that.isGps = res.locationEnabled ? res.locationEnabled : ''
          console.log('设备参数设置 Wifi：' + res.wifiEnabled + ' Gps:' + res.locationEnabled)
          if (callback) {
            callback()
          }
        }
      })
    },

    //启用wifi模块
    startWifi(callback) {
      wx.startWifi({
        success: function (e) {
          callback()
        },
        fail: function (e) {}
      })
    },
    //获取到了设备数据
    connection(callback) {
      var that = this
      wx.getConnectedWifi({
        success: function (e) {
          console.log(e, 'wifi数据')
          that.info.WifiName = e.wifi.SSID
          that.info.WifiCode = e.wifi.BSSID
          console.log('🚀 ~ file: punchtheclock.vue ~ line 298 ~ connection ~ that.info', that.info)
          if (callback) {
            callback()
          }
        },
        fail: function (e) {
          if (e.errCode == '12005') {
            wx.showModal({
              title: '提示',
              content: '请连接WiFi',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else if (e.errCode == '12006') {
            wx.showModal({
              title: '提示',
              content: '请打开手机 GPS 定位开关',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
          if (callback) {
            callback()
          }
        }
      })
    }
  },
  mounted() {}
  //onHide:{},  //监听页面隐藏
  //onUnload:{},	//监听页面卸载
  //onPullDownRefresh:{},  //监听用户下拉动作，一般用于下拉刷新  page.json  "enablePullDownRefresh":true,//开启下拉刷新
  //onReachBottom:{}, //页面滚动到底部
  //onShareAppMessage:{}, 用户点击右上角分享
}
</script>

<style scoped lang="scss">
.clockBox {
  .stitle {
    padding: 30rpx;
    box-sizing: border-box;
    font-size: 32rpx;
    font-weight: 500;
    color: #333333;
  }
  .toprow {
    padding: 38rpx 0 0 0;
  }
  .left {
    width: 70rpx;
    .dian {
      width: 16rpx;
      height: 16rpx;
      background: #d8d8d8;
      margin: 0 auto;
      border-radius: 50%;
    }
    .line {
      width: 2rpx;
      height: 20rpx;
      background: rgba(0, 0, 0, 0.4);
    }
  }
  .time {
    font-size: 26rpx;
    font-weight: 400;
    color: #999999;
    line-height: 36rpx;
  }
  .ctime {
    font-size: 30rpx;
    font-weight: 500;
    color: #333333;
    line-height: 42rpx;
    padding: 14rpx 0 4rpx 0;
  }
  .wifi {
    width: 44rpx;
    height: 22rpx;
    background: #4c7699;
    text-align: center;
    line-height: 22rpx;
    border-radius: 10rpx;
    margin-right: 10rpx;
    font-size: 22rpx;
    color: #ffffff;
  }
  .sinfo {
    width: 680rpx;
    margin-left: 35rpx;
    border-left: 2rpx solid rgba(0, 0, 0, 0.4);
  }
}
.boxcolor {
  background: #2b88fe;
  padding: 35upx 30upx;
}

.l_text {
  color: #fff;
  font-size: 26upx;
}

.itemna {
  color: #fff;
  font-size: 30upx;
  padding: 0 20upx;
}

.shownyber {
  background: #2b88fe;
  text-align: center;
  color: #fff;
  font-size: 26upx;
  padding-bottom: 30upx;
}

.nunber {
  font-size: 40upx;
}

.punchtheclock {
  padding: 0 32upx;
  border-bottom: 1px solid #f1f1f1;
  padding-bottom: 50upx;
}

.layers {
  padding-left: 25upx;
  position: relative;

  .icondizhi2 {
    font-size: 40rpx;
    color: #d8d8d8;
    margin-right: 10rpx;
  }

  .waibox {
    width: 88rpx;
    height: 44rpx;
    border-radius: 4rpx;
    border: 2rpx solid #22bfb6;
    color: #22bfb6;
    font-size: 30rpx;
    text-align: center;
    line-height: 44rpx;
    margin-left: 16rpx;
    margin-top: 10rpx;
  }

  .statusbox {
    width: 88rpx;
    height: 44rpx;
    border-radius: 4rpx;
    border: 2rpx solid #ff930a;
    color: #ff930a;
    font-size: 30rpx;
    text-align: center;
    line-height: 44rpx;
    margin-left: 16rpx;
    margin-top: 10rpx;
  }
}

.text1,
.text4 {
  color: #999;
  font-size: 26upx;
  position: relative;
}

.text2 {
  color: #333;
  font-size: 30upx;
  padding-top: 15upx;
}

.text3 text {
  color: #fff;
  font-size: 22upx;
  background: #4c7699;
  padding: 0 10upx;
  border-radius: 10upx;
  margin-right: 10upx;
}

.text3 {
  color: #979797;
  font-size: 26upx;
  padding-top: 5upx;
}

.text1::after {
  content: '';
  width: 16upx;
  height: 16upx;
  border-radius: 8upx;
  position: absolute;
  left: -32upx;
  top: 20rpx;
  z-index: 2;
  margin-top: -8upx;
  background: #d8d8d8;
}
.text4::after {
  background: #18b566;
}
.layers::after {
  content: '';
  width: 1px;
  background: #999;
  height: 60%;
  position: absolute;
  left: 0px;
  top: 27rpx;
}

.buttonbox {
  width: 212upx;
  height: 212upx;
  padding-top: 62upx;
  box-shadow: 0 30upx 50upx #bbddec;
  background: linear-gradient(136deg, #3992f6 0%, #0fb6fe 100%);
  margin: auto;
  border-radius: 150upx;
  margin-top: 88upx;
  text-align: center;
  color: #fff;
}
</style>
